import React, { Component } from 'react'
export default class TreeStore {
  constructor (options) {
    this.data = options.data
    this.setChecked = this.setChecked.bind(this)
  }
  setChecked (node, val) {
    this.verifySelfAndChild(node, (u) => {
      u.props.data.checked = val
      if (!val) {
        u.state.isSemi = false
      }
    })
    this.verifyParent(node, (u) => {
      if (val) {
        u.props.data.checked = val
      } else {
        if (u.props.data.children && u.props.data.children.every(k => !k.checked)) { // 如果子全部不选
          u.props.data.checked = false
        }
      }
      u.state.isSemi = this.isSemi(u)
    })
  }
  mountedSemi (node) {
    this.verifyParent(node, (u) => {
      u.state.isSemi = this.isSemi(u)
      u.setState({})
    })
  }
  isSemi (u) {
    let isSemi = false
    u.state.childrenNode.forEach((k, index) => {
      if (k.state.isSemi || (u.props.data.checked && !k.props.data.checked)) {
        isSemi = true
      }
    })
    return isSemi
  }
  verifyParent (node, cb) {
    if (node.context.TreeNode) { // get parent
      cb(node.context.TreeNode)
      this.verifyParent(node.context.TreeNode, cb)
    }
  }
  verifyChild (node, cb) {
    node.state.childrenNode && node.state.childrenNode.forEach((u, index) => {
      cb(u)
      if (u.state.childrenNode) {
        this.verifyChild(u, cb)
      }
    })
  }
  verifySelfAndChild (node, cb) {
    cb(node)
    if (node.state.childrenNode) {
      node.state.childrenNode.forEach((u, index) => {
        this.verifySelfAndChild(u, cb)
      })
    }
  }
}